package org.dreamfly.core.util;

import java.io.FileOutputStream;
import java.io.RandomAccessFile;

/**
 * Created by IntelliJ IDEA.
 * User: Gin
 * Date: 2010-10-13
 * Time: 9:59:04
 * To change this template use File | Settings | File Templates.
 */
public class creatVideoFile {
    /**
   *
   *
     * @param fileAndPath 原文件及完整路径
     * @param fileSeparateName 文件分隔后要生成的文件名，与原文件在同一个目录下
     * @param blockSize 当前块要写的字节数
     * @param beginPos 从原文件的什么地方开始读取
     * @param headLength
     * @return true为写入成功，false为写入失败
   */
  public boolean writeFile(String fileAndPath, String fileSeparateName, long blockSize, long beginPos, int headLength)//往硬盘写文件
  {

    RandomAccessFile raf=null;
    FileOutputStream fos=null;
    byte[] bt=new byte[1024];
    byte[] head = new byte[headLength];   //
    byte[] foot = {0,0,1, (byte) 0xB1};
    long writeByte=0;     //已写字节数
    int len=0;
    try
    {
      raf = new RandomAccessFile(fileAndPath,"r");
      fos = new FileOutputStream(fileSeparateName);
      raf.seek(0);
      raf.read(head);
      fos.write(head);
      raf.seek(beginPos);  

      while((len=raf.read(bt))>0)
      {
        if(writeByte<blockSize)//如果当前块还没有写满
        {
          writeByte=writeByte+len;
          if(writeByte<=blockSize)
            fos.write(bt,0,len);
          else
          {
            len=len-(int)(writeByte-blockSize);
            fos.write(bt,0,len);
          }
        }
      }
      fos.write(foot);
      fos.close();
      raf.close();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      try
      {
        if(fos!=null)
          fos.close();
        if(raf!=null)
          raf.close();
      }
      catch(Exception f)
      {
        f.printStackTrace();
      }
      return false;
    }
    return true;
  }
}
